<template>
  <div class="container">
    <div>
      <a-row>
        <a-col :span="8">
          <p>体温异常: {{temperatureException}}人</p>
        </a-col>
        <a-col :span="8">
          <p>两周内曾(疑)接触过感染源: {{isContactNum}}人</p>
        </a-col>
        <a-col :span="8">
          <p>两周内去过国外: {{isArriveNum}}人</p>
        </a-col>
      </a-row>
    </div>
    <h1 style="font-size: 22px">住户健康数据统计</h1>
    <div>
      <a-dropdown>
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="近一周"> <a-icon type="calendar" />近一周 </a-menu-item>
          <a-menu-item key="近30天"> <a-icon type="calendar" />近30天 </a-menu-item>
          <a-menu-item key="近90天"> <a-icon type="calendar" />近90天 </a-menu-item>
          <a-menu-item key="至今"> <a-icon type="calendar" />至今 </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> {{selectText}} <a-icon type="down" /> </a-button>
      </a-dropdown>
    </div>
    <a-row>
      <a-col :span="20">
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="tableToExcel" style="margin-bottom: 15px; font-size: 18px">
          导出excel表
        </a-button>
      </a-col>
    </a-row>
    <a-table :data-source="data" :columns="columns" :rowKey="record => record.healthId"
             @change="onChange">
      <div
        slot="filterDropdown"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-input
          v-ant-ref="c => (searchInput = c)"
          :placeholder="`Search ${column.dataIndex}`"
          :value="selectedKeys[0]"
          style="width: 188px; margin-bottom: 8px; display: block;"
          @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
        >
          Search
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
          Reset
        </a-button>
      </div>
      <a-icon
        slot="filterIcon"
        slot-scope="filtered"
        type="search"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />

      <template slot="customRender" slot-scope="text, record, index, column">
        <span v-if="searchText && searchedColumn === column.dataIndex">
          <template
            v-for="(fragment, i) in text
              .toString()
              .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
          >
            <mark
              v-if="fragment.toLowerCase() === searchText.toLowerCase()"
              :key="i"
              class="highlight"
            >{{ fragment }}</mark
            >
            <template v-else>{{ fragment }}</template>
          </template>
        </span>
        <template v-else>
          {{ text }}
        </template>
      </template>

    </a-table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: [],
      saveData: [],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      columns: [
        {
          title: '姓名',
          dataIndex: 'resident.name',
          key: 'resident.name',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.resident.name
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '电话',
          dataIndex: 'resident.phone',
          key: 'resident.phone',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.resident.phone
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '体温',
          dataIndex: 'temperature',
          key: 'temperature',
          sorter: (a, b) => a.temperature - b.temperature
        },
        {
          title: '近两周是否接触过感染源',
          dataIndex: 'isContact',
          key: 'isContact',
          customRender: function (text) {
            if (text === 0) {
              return '否'
            } else {
              return '是'
            }
          },
          filters: [
            {
              text: '否',
              value: 0
            },
            {
              text: '是',
              value: 1
            }
          ],
          onFilter: (value, record) => record.isContact === value
        },
        {
          title: '近两周是否去过国外',
          dataIndex: 'isArrive',
          key: 'isArrive',
          customRender: function (text) {
            if (text === 0) {
              return '否'
            } else {
              return '是'
            }
          },
          filters: [
            {
              text: '否',
              value: 0
            },
            {
              text: '是',
              value: 1
            }
          ],
          onFilter: (value, record) => record.isArrive === value
        },
        {
          title: '目前健康状态',
          dataIndex: 'resident.status',
          key: 'resident.status',
          customRender: function (text) {
            if (text === 0) {
              return '健康'
            } else if (text === 1) {
              return '预警'
            } else {
              return '高危'
            }
          },
          filters: [
            {
              text: '健康',
              value: 0
            },
            {
              text: '预警',
              value: 1
            },
            {
              text: '高危',
              value: 2
            }
          ],
          onFilter: (value, record) => record.resident.status === value
        },
        {
          title: '时间',
          dataIndex: 'time',
          key: 'time',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          sortDirections: ['ascend', 'descend'],
          onFilter: (value, record) =>
            record.time
              .toString()
              .includes(value),
          // 自动添加输入焦点
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          },
          sorter: (a, b) => new Date(a.time) - new Date(b.time)
        }
      ],
      visible: false,
      // 统计数据
      temperatureException: 0,
      isContactNum: 0,
      isArriveNum: 0,
      selectText: '至今'
    }
  },
  created () {
    this.$http.get('/healths')
      .then((resp) => {
        if (resp.body.status === 401) {
          this.$message.error('请先登录')
          this.$router.push('/login')
        } else {
          this.data = resp.body.data.filter(item => item.resident.isResident === 1)
          this.saveData = resp.body.data.filter(item => item.resident.isResident === 1)
          this.statistics()
        }
      }, (error) => {
        if (error.status === 401) {
          this.$message.error('请先登录')
          this.$router.push('/login')
        } else {
          this.$message.error('请保持网络通畅')
        }
      })
  },
  methods: {
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },

    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },

    onChange (pagination, filters, sorter) {
    },

    handleMenuClick ({ key }) {
      this.getDay(-30)
      if (key === '近一周') {
        this.changeShowData(-7)
      } else if (key === '近30天') {
        this.changeShowData(-30)
      } else if (key === '近90天') {
        this.changeShowData(-90)
      } else {
        this.data = this.saveData
      }
      this.statistics()
      this.selectText = key
    },
    getDay (day) {
      var today = new Date()
      var targetdayMilliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(targetdayMilliseconds)
      return today
    },
    changeShowData (day) {
      var limitDay = this.getDay(day)
      const newData = [...this.saveData]
      this.data = newData.filter(item => new Date(item.time) > limitDay)
    },
    statistics () {
      var temperatureArr = []
      var contactArr = []
      var arriveArr = []
      this.data.forEach((item) => {
        if (item.temperature > 37) {
          temperatureArr.push(item.resident.openid)
        }
        if (item.isContact) {
          contactArr.push(item.resident.openid)
        }
        if (item.isArrive) {
          arriveArr.push(item.resident.openid)
        }
      })
      const temperatureArr1 = [...new Set(temperatureArr)]
      const contactArr1 = [...new Set(contactArr)]
      const arriveArr1 = [...new Set(arriveArr)]
      this.temperatureException = temperatureArr1.length
      this.isContactNum = contactArr1.length
      this.isArriveNum = arriveArr1.length
    },
    tableToExcel () {
      let str = '<tr><td>姓名</td><td>电话</td><td>体温</td><td>近两周是否接触过感染源</td><td>近两周是否去过国外</td><td>健康状态</td><td>时间</td></tr>'
      // 循环遍历，每行加入tr标签，每个单元格加td标签
      for (let i = 0; i < this.data.length; i++) {
        str += '<tr>'
        str += `<td>${this.data[i].resident.name + '\t'}</td>`
        str += `<td>${this.data[i].resident.phone + '\t'}</td>`
        str += `<td>${this.data[i].temperature + '\t'}</td>`
        if (this.data[i].isContact === 0) {
          str += '<td>否</td>'
        } else {
          str += '<td>是</td>'
        }
        if (this.data[i].isArrive === 0) {
          str += '<td>否</td>'
        } else {
          str += '<td>是</td>'
        }
        if (this.data[i].resident.status === 0) {
          str += '<td>健康</td>'
        } else if (this.data[i].resident.status === 1) {
          str += '<td>预警</td>'
        } else {
          str += '<td>高危</td>'
        }
        str += `<td>${this.data[i].time + '\t'}</td>`
        str += '</tr>'
      }
      // Worksheet名
      const worksheet = '住户健康信息表'
      const uri = 'data:application/vnd.ms-excel;base64,'

      // 下载的表格模板数据
      const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40" lang="en">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`
      // 下载模板
      const link = document.createElement('a')
      link.href = uri + this.base64(template)
      // 对下载的文件命名
      link.download = '住户健康信息表.xls'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    base64 (s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    }
  }
}
</script>
<style scoped>
  .highlight {
    background-color: rgb(255, 192, 105);
    padding: 0;
  }
  p {
    font-size: 18px;
  }
</style>
